package pl.edu.pw.ee.buildcity.scheduler.strategies;

import pl.edu.pw.ee.buildcity.commons.exceptions.BuildCityRuntimeException;
import pl.edu.pw.ee.buildcity.entities.BuildActivity;
import pl.edu.pw.ee.buildcity.scheduler.BuildContext;
import pl.edu.pw.ee.buildcity.scm.subversion.SVNCheckoutParameters;

import java.io.File;

/**
 * @author Mateusz
 * @since 2010-02-28
 */
public class FreshBuildStrategy extends BuildStrategy {

	public FreshBuildStrategy(BuildContext context, File workingCopy) {
		super(context, workingCopy);
	}

	@Override
	public void preProcess() {
		BuildActivity registeredActivity = buildActivityService.registerFreshBuildActivityStart(buildCtx.getBuildName());
		buildCtx.setBuildActivity(registeredActivity);
	}

	@Override
	public void performBuild() throws BuildCityRuntimeException {
		log.info("Working copy not found or clean build requested. Performing fresh checkout and build...");
		if (workingCopy.exists()) {
			deleteDirectory(workingCopy);
		}
		workingCopy = checkoutHEAD(buildCtx);
		runMaven2Build();
	}

	@Override
	public void postProcess() {
		buildPostProcessing.performPostProcessing(buildCtx);
	}

	private void deleteDirectory(File workingCopy) {
		try {
			if (workingCopy.exists()) {
				File[] files = workingCopy.listFiles();
				for (int i = 0; i < files.length; i++) {
					if (files[i].isDirectory()) {
						deleteDirectory(files[i]);
					} else {
						files[i].delete();
					}
				}
			}
			if (!workingCopy.delete()) {
				throw new BuildCityRuntimeException("Could not delete directory: " + workingCopy);
			}
		} catch (Exception e) {
			String msg = "Error while deleting working copy: " + workingCopy;
			log.error(msg, e);
			throw new BuildCityRuntimeException(msg, e);
		}
	}

	private File checkoutHEAD(BuildContext context) {
		String url = context.getUrlToCheckout();
		String workingCopyLocation = context.getWorkingCopyLocation();

		SVNCheckoutParameters checkoutParameters = SVNCheckoutParameters.checkoutHEAD(url);
		return svnService.checkout(checkoutParameters, workingCopyLocation);
	}
}
